import { useDockerApiPathWithout } from '@/stores/dockerApi'
import axios, { AxiosRequestConfig } from 'axios'

interface AxiosReqTy extends AxiosRequestConfig {
  url?: string
  method?: string
  data?: Record<string, any>
  params?: Record<string, any>
  baseURL?: string
  timeout?: number
}

interface AxiosConfigTy {
  url?: string
  method?: string
  data?: Record<string, any>
  params?: Record<string, any>
  baseURL?: string
  timeout?: number
}

let reqConfig: any

const service: any = axios.create()

// 请求拦截
service.interceptors.request.use(
  (request: AxiosReqTy) => {
    const dockerAPIStore = useDockerApiPathWithout()
    // console.log(dockerAPIStore.router);
    
    request.baseURL = `/${dockerAPIStore.router}`

    /*
     *params会拼接到url上
     * */
    reqConfig = request
    return request
  },
  (err: any) => {
    Promise.reject(err)
  }
)
// 响应拦截
service.interceptors.response.use(
  (res: any) => {
    const code = res.status
    const successCode = '0,200,201,204,304,20000'
    if (successCode.includes(code)) {
      return res?.data ?? res
    } else {
      //返回错误信息
      return Promise.reject(res?.data ?? res)
    }
  },
  (err: any) => {
    //如果是跨域
    const errObj: Record<string, any> = {
      server_error_message: err.message.toString(),
      message: err.response?.data?.message ?? '',
      reqUrl: reqConfig.baseURL + reqConfig.url,
      params: reqConfig.isParams ? reqConfig.params : reqConfig.data
    }
    return Promise.reject(JSON.stringify(errObj))
  }
)

export async function axiosReq({ url, data, method, params, baseURL, timeout }: AxiosConfigTy): Promise<any> {
  return service({
    url: url,
    method: method ?? 'get',
    data: data ?? {},
    params: params ?? {},
    //baseURL: baseURL ?? '/docker-api',
    timeout: timeout ?? 15000
  })
}

export default axiosReq
export { service as axiosInstance }
